""" blue print for decorator """
from functools import wraps
import time
import numpy

# def timer(func, *args, **kwargs):
#     # 包裹,保证不被覆盖
#     @wraps(func)
#     def timer_it(*args):
#         start = time.time()
#         res = func(*args)
#         end = time.time()
#         print(f"do function {func.__name__} used time {end-start} seconds")
#         return res
#     return timer_it

# @timer
# def check(num):
#     ans = []
#     for i in range(num):
#         ans.append(i)
#     return ans

# @timer
# def check_2():
#     time.sleep(2)
#     return "finished"

# print(check(10))
# print(check_2())
# print(check.__name__)


# 标准装饰器模板
def decorator(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return f"Function {f.__name__} can not run"
        return f(*args, **kwargs)
    return decorated

@decorator
def func(n, flag = "good"):
    ans = []
    for i in range(n):
        ans.append(i)
    print(f"{flag}")
    return ans 

can_run = True
print(func(3), func.__name__)

# 函数实现日志装饰器模板:
from functools import wraps

def logit(file = "out.log"):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__+"was called"
            print(log_string)
            with open(file, "w") as f:
                f.write(log_string)
            
            return func(*args, **kwargs)
        return wrapped_function
    return logging_decorator

#test
# @logit()
# def myfunc1():
#     pass
# myfunc1()
